package com.hzlx.controller;/*
 *@author liu
 *2024/07/2024/7/30
 *@version
 */

import com.hzlx.common.ResponseBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author UP
 * @Date 2024/7/30 11:34
 * @Version 1.0
 **/

@Controller
@RequestMapping("/fileUpload")
public class UploadController {
    @PostMapping("/imgShow")
    @ResponseBody
    public ResponseBean fileUploadAsync(MultipartFile file, HttpServletRequest request) {
        //设置文件存储位置
        //获取当前项目的目录路径
        String filePathDir = request.getServletContext().getRealPath("/upload");
        //根据路径的url创建url文件夹
        File dir = new File(filePathDir);
        if (!dir.exists()) {
            dir.mkdir();
        }

        //获取当前文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //使用UUID生成文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        //实例化File对象
        File newFile = new File(dir, newFileName + suffix);
        String fileType = file.getContentType();
        String type = fileType.substring(0, fileType.lastIndexOf("/"));
        if (!"image".equals(type)) {
            return new ResponseBean(10011, "文件不是图片", null);
        }
        //持久化到硬盘
        try {
            file.transferTo(newFile);
            String loadPath = request.getContextPath() + "/upload/" + newFileName + suffix;
            String fileName = newFileName+suffix;
//            String loadPath = request.getContextPath() + "/upload/" + newFileName + suffix;
            return new ResponseBean(0, "success", fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseBean(10012, "文件上传失败", null);
    }
}

